package cn.b.sky.form.service.impl;

import cn.b.sky.common.utils.FTPUtils;
import cn.b.sky.common.utils.SkyFileUtils;
import cn.b.sky.common.utils.SpringBeanUtil;
import cn.b.sky.form.dao.BusinessAttachmentDao;
import cn.b.sky.form.model.BusinessAttachment;
import cn.b.sky.form.service.BusinessAttachmentService;
import cn.b.sky.user.model.Attachment;
import cn.b.sky.user.service.AttachmentService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service("businessAttachmentService")
public class BusinessAttachmentServiceImpl implements BusinessAttachmentService {

  private static final Logger LOGGER = LoggerFactory.getLogger(BusinessAttachmentServiceImpl.class);
  
  @Resource
  AttachmentService attachmentService;
  
  @Autowired
  BusinessAttachmentDao businessAttachmentDao;
  
  @Override
  public BusinessAttachment saveBusinessAttachmentAttach(BusinessAttachment attachment, MultipartFile file) {
   
    if (attachment != null && !StringUtils.isBlank(attachment.getSiteCode())) {
      String filePath = SkyFileUtils.buildFilePath("productionOrder");
      String fileName = file.getOriginalFilename();
      String md5 = "";
      try {
        md5 = SkyFileUtils.getMD5String(file.getBytes());
      } catch (IOException e) {
        LOGGER.error("{}", e);
      }
      attachment.setFileName(fileName);
      attachmentService.checkIsExtisAttachment(attachment, md5);
      //MD5校验，映射文件
      if (StringUtils.isBlank(attachment.getAttachmentCode())) {
        String saveName = UUID.randomUUID().toString();
        String newFileName = SkyFileUtils.renameFileName(fileName, saveName);
        FTPUtils ftpUtils = (FTPUtils) SpringBeanUtil.getBean("ftpUtils");
        String savePath = ftpUtils.uploadMultipartFiles(file, filePath, newFileName);
        Long size = file.getSize();
        attachment.setAttachmentCode(saveName);
        attachment.setFileSize(size);
        attachment.setSavePath(savePath);
        Attachment att = new Attachment(saveName, savePath, fileName, size, md5, 1);
        att.setSiteCode(attachment.getSiteCode());
        attachmentService.insertAttachment(att);
      }
      return attachment;
    }
    return null;

  }

  @Override
  public List<BusinessAttachment> getBusinessAttachments(BusinessAttachment businessAttachment) {
    
    return businessAttachmentDao.selectBusinessAttachment(businessAttachment);
  }

}
